package edu.rakovic.elearning.pages;

import org.apache.tapestry5.Block;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;

import edu.rakovic.elearning.beans.CourseBean;
import edu.rakovic.elearning.enums.Role;
import edu.rakovic.elearning.interfaces.Course;
import edu.rakovic.elearning.interfaces.User;
import edu.rakovic.elearning.service.Courses;

public class AddCourse {
	
	
	@Property
	@Inject
	private Block add;
	
	@Property
	@Inject
	private Block congratulations;
	
	@Property
	private String name;
	@Property
	private String shortDescription;
	
	
	@Inject
	private Courses courses;
	
	//both components are for validation purpose
	@Component
	private Form courseInputForm;
	@Component(id="courseName")
	private TextField courseNameField;
	
	Object onValidateForm(){
		if(courses.retreiveSingleCourse(name) == null){
			Course course = new CourseBean();
			course.createCourse(name, shortDescription, user);
			courses.save(course);
			return congratulations;
		} else {
			courseInputForm.recordError(courseNameField,"Cannot create - course with that name already exists!");
			return add;
		}
	}


//	@OnEvent (value="submit", component="courseInputForm")
//	Object onFromSubmit(){
//	
//		Course course = new CourseBean();
//		course.executeCourseCreation(name, shortDescription, user);
//		courses.save(course);
//		return ViewTeachingCourses.class;	
//
//	}
	
	//Making sure that no one except teacher can add course.
	@SessionState
	private User user;

	private boolean userExists;
	
	public User getUser() {
		return user;
	}
	
	Object onActivate() {
		if (!userExists) return Login.class;
		if (getUser().getRole()!= Role.TEACHER) return Index.class;
		return null;
	}

	
}